package com.krtech.wecard.module.sys.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.codec.Base32;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.module.pub.entity.ApplicationManagement;
import com.krtech.wecard.module.pub.service.ApplicationManagementService;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.pojo.AuthEntity;
import com.krtech.wecard.module.sys.service.SysConfigurationService;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 配置管理
 */
@RestController
@RequestMapping("/sys/configuration")
@Api(value = "配置管理")
public class SysConfigurationController {

    @Autowired
    private SysConfigurationService configurationService;

    @Autowired
    private SysKeyValueService keyValueService;

    @Autowired
    private ApplicationManagementService applicationManagementService;

    /**
     * 提供对接
     *
     * 通过给定的appId 以及key和secret获得token
     */
    @GetMapping("/getAccessToken")
    @ApiOperation(value = "通过给定的appId 以及key和secret获得token")
    @Inner(value = false)
    public SaTokenInfo getAccessToken(AuthEntity authEntity){
        String appId = authEntity.getAppId();
        if (StrUtil.isEmpty(appId)){
            //todo 没有appId，走全局鉴权
        }else {
            //找到对应的模块情况
            ApplicationManagement applicationManagement = applicationManagementService.getOne(new QueryWrapper<ApplicationManagement>()
                    .eq(ApplicationManagement.COL_ID, appId)
                    .eq(ApplicationManagement.COL_APP_KEY, authEntity.getAppKey())
                    .eq(ApplicationManagement.COL_APP_SECRET, authEntity.getAppSecret()));

            if (applicationManagement == null){
                throw new BusinessException("给定参数无法通过鉴权");
            }
        }
        //获得token信息
        SaTokenInfo saTokenInfo = configurationService.simulationLogin();
        return saTokenInfo;
    }


    /**
     * 生成新的全局接口调用key和secret
     */
    @GetMapping("/generateGlobalKeyAndSecret")
    @ApiOperation(value = "生成新的全局接口调用key和secret")
    public SysKeyValue generateGlobalKeyAndSecret(){
        // 生成的钥匙对相同
        String appKey = IdUtil.simpleUUID();
        String encode = Base32.encode(appKey);
        String secret = encode.substring(0, 32);

        SysKeyValue globalKeyAndSecret = keyValueService.getOne(new QueryWrapper<SysKeyValue>().eq(SysKeyValue.COL_SYS_NAME, SysEnums.GLOBAL_KEY_AND_SECRET));
        if (globalKeyAndSecret == null){
            SysKeyValue sysKeyValue = new SysKeyValue();
            sysKeyValue.setSysName(SysEnums.GLOBAL_KEY_AND_SECRET);
            sysKeyValue.setCreatedTime(new Date());
            sysKeyValue.setSysKey(appKey);
            sysKeyValue.setSysValue(secret);
            sysKeyValue.setRemark("全局key和secret");

            keyValueService.save(sysKeyValue);
            return sysKeyValue;
        }else {
            globalKeyAndSecret.setCreatedTime(new Date());
            globalKeyAndSecret.setSysKey(appKey);
            globalKeyAndSecret.setSysValue(secret);
            globalKeyAndSecret.setRemark("全局key和secret");
            keyValueService.updateById(globalKeyAndSecret);
            return globalKeyAndSecret;
        }
    }

    @GetMapping("/getGlobalKeyAndSecret")
    @ApiOperation(value = "获得全局接口调用key和secret")
    public SysKeyValue getGlobalKeyAndSecret(){
        SysKeyValue globalKeyAndSecret = keyValueService.getOne(new QueryWrapper<SysKeyValue>().eq(SysKeyValue.COL_SYS_NAME, SysEnums.GLOBAL_KEY_AND_SECRET));
        return globalKeyAndSecret;
    }



    @PutMapping("/add")
    @ApiOperation(value = "add")
    public SysKeyValue add(@RequestBody SysKeyValue sysKeyValue){
        if (StrUtil.isEmpty(sysKeyValue.getSysKey()) || StrUtil.isEmpty(sysKeyValue.getSysValue())){
            throw new BusinessException("必填参数key和value不能为空");
        }
        //保证key没有重复
        int count1 = keyValueService.count(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_KEY, sysKeyValue.getSysKey()));

        int count2 = keyValueService.count(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME,sysKeyValue.getSysName()));

        if (count1 > 0 || count2 > 0){
            throw new BusinessException("您添加的配置key已经存在，不能重复添加");
        }
        keyValueService.save(sysKeyValue);
        return sysKeyValue;
    }

    @PutMapping("/update")
    @ApiOperation(value = "update")
    public SysKeyValue update(@RequestBody SysKeyValue sysKeyValue){
        if (StrUtil.isEmpty(sysKeyValue.getSysKey()) || StrUtil.isEmpty(sysKeyValue.getSysValue())){
            throw new BusinessException("必填参数key和value不能为空");
        }
        SysKeyValue valueServiceOne = keyValueService.getOne(new QueryWrapper<SysKeyValue>().eq(SysKeyValue.COL_SYS_KEY, sysKeyValue.getSysKey()));
        valueServiceOne.setSysValue(sysKeyValue.getSysValue());
        //保证key没有重复
        keyValueService.updateById(valueServiceOne);
        return valueServiceOne;
    }


    @GetMapping("/query")
    @ApiOperation(value = "query")
    @Inner(value = false)
    public SysKeyValue query(SysKeyValue sysKeyValue){
        if (StrUtil.isEmpty(sysKeyValue.getSysName()) && (sysKeyValue.getId() != null) && StrUtil.isEmpty(sysKeyValue.getSysKey())){
            throw new BusinessException("必填参数name或者Id不能为空");
        }

        QueryWrapper<SysKeyValue> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(sysKeyValue.getSysName())){
            wrapper.eq(SysKeyValue.COL_SYS_NAME,sysKeyValue.getSysName());
        }

        if (sysKeyValue.getId() != null){
            wrapper.eq(SysKeyValue.COL_ID,sysKeyValue.getId());
        }

        if (StrUtil.isNotEmpty(sysKeyValue.getSysKey())){
            wrapper.eq(SysKeyValue.COL_SYS_KEY,sysKeyValue.getSysKey());
        }


        SysKeyValue keyValue = keyValueService.getOne(wrapper);
        return keyValue;
    }

}
